package br.com.playonline.persistencia;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import org.springframework.stereotype.Component;

@Component
public class HibernateDAOGenerico<T, ID extends Serializable> extends
		HibernateDaoSupport implements GenericDAO<T, Serializable> {

	private static Log LOG = LogFactory.getLog(HibernateDAOGenerico.class);
	
	SessionFactory sessionFactory;
	
	@Autowired
	public HibernateDAOGenerico(SessionFactory sessionFactory) {
		setSessionFactory(sessionFactory);
	}

	private Class<T> persistenteClass;
	@SuppressWarnings("unchecked")
	public Class<T> getPersistenteClass() {
		this.persistenteClass = (Class<T>) ((ParameterizedType) getClass()
				.getGenericSuperclass()).getActualTypeArguments()[0];
		return this.persistenteClass;
	}

	public T findById(Serializable id) {
		try{
			return this.getHibernateTemplate().get(getPersistenteClass(), id);
		}catch(HibernateException exception){
			HibernateDAOGenerico.LOG.error(exception);
		}
		return null;
	}

	public List<T> findAll() {
		return getHibernateTemplate().loadAll(getPersistenteClass());
	}

	public T save(T entity) {
		
		getHibernateTemplate().save(entity);
		return entity;
	}

	public void delete(T entity) {
		getHibernateTemplate().delete(entity);
	}

	@SuppressWarnings("unchecked")
	protected List<T> findByCriteria(Criterion... criterion) {
		Criteria crit = this.getHibernateTemplate().getSessionFactory()
				.getCurrentSession().createCriteria(getPersistenteClass());
		for (Criterion c : criterion) {
			crit.add(c);
		}
		return crit.list();
	}

}
